package jp.com.nobnak.commentviewer.net;

import java.io.IOException;

import jp.com.nobnak.commentviewer.common.IAction1;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;

import android.os.AsyncTask;

public class AsyncRequest extends AsyncTask<HttpUriRequest, Void, HttpResponse> {
	private HttpContext mContext;
	private IAction1<HttpResponse> mResult;
	private IAction1<AsyncRequestException> mError;
	private IPostExecute mPostExecute;
	
	public AsyncRequest(HttpContext context, 
			IAction1<HttpResponse> result, 
			IAction1<AsyncRequestException> error) {
		mContext = context;
		mResult = result;
		mError = error;
	}
	
	@Override
	protected HttpResponse doInBackground(HttpUriRequest... requests) {
		try {
			if (requests.length <= 0)
				throw new AsyncRequestException("No parameters set");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(requests[0], mContext);
			mPostExecute = new ResultHandler();
			return response;
		} catch (ClientProtocolException e) {
			mPostExecute = new ErrorHandler(
					new AsyncRequestException(e.getMessage()));
		} catch (IOException e) {
			mPostExecute = new ErrorHandler(
					new AsyncRequestException(e.getMessage()));
		} catch (AsyncRequestException e) {
			mPostExecute = new ErrorHandler(e);
		}
		return null;
	}

	@Override
	protected void onPostExecute(HttpResponse result) {
		try {
			mPostExecute.call(result);
		} catch (Exception e) {
			mPostExecute = new ErrorHandler(new AsyncRequestException(e.getMessage()));
			mPostExecute.call(result);
		}
	}
	
	private interface IPostExecute extends IAction1<HttpResponse> {}
	private class ErrorHandler implements IPostExecute {
		private AsyncRequestException mException;
		
		public ErrorHandler(AsyncRequestException e) {
			mException = e; 
		}
		@Override
		public void call(HttpResponse param1) {
			try {
				AsyncRequest.this.mError.call(mException);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	private class ResultHandler implements IPostExecute {
		@Override
		public void call(HttpResponse param1) {
			AsyncRequest.this.mResult.call(param1);
		}
	}
}
